<template>
  <div class="app-container" v-loading="pageLoading">
    <el-row :gutter="10">
      <el-col :span="12">
        <div class="panel-info">
          <div class="panel-title">字典类型列表</div>
          <div class="panel-body">
            <el-button type="primary" class="fr" @click="createItem" v-permission="'adminDictionary.add'">创建</el-button>
            <div class="filter-container">
              <el-input style="width: 300px;" placeholder="输入查询条件按回车" clearable prefix-icon="el-icon-search"
                class="filter-item" @keyup.enter.native="research" @clear="research" v-model="query.queryString">
              </el-input>
              <el-button class="filter-item" type="success" plain @click="research">查询</el-button>
              <el-button class="filter-item" type="info" plain @click="exportData" :loading="exportLoading">导出
              </el-button>
            </div>
            <z-table :list="list" :tableProps="tableProps" @current-change="getChildrenTree" :columns="columns">
              <template v-slot:operation="v">
                <a href="#" class="text-blue" @click.prevent.stop="editItem(v.row)"
                  v-if='isSuper ||v.row.is_system !=  "Y"'>编辑</a>
                <a href="#" class="text-blue" v-else>　　　　</a>
                <a v-if='isSuper ||v.row.is_system !=  "Y"' style="margin-left:5px;" href="#" class="text-red"
                  @click.prevent.stop="deleteItem(v.row)">删除</a>
                <a href="#" class="text-blue" v-else>　　　　</a>

              </template>
            </z-table>
            <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
              @change="getList"></z-pagination>
          </div>
        </div>
      </el-col>
      <el-col :span="12" v-if="currentDataId">
        <div class="panel-info">
          <div class="panel-title">字典详情</div>
          <div class="panel-body">
            <el-button class="fr" type="success"
              v-if="currentDataId && indexChangeFlag && (isSuper || isSystemFlag != 'Y')"
              v-permission="'adminDictionary.edit'" @click="saveIndex">保存排序
            </el-button>
            <div style="padding: 10px 0;min-height: 40px;" v-if="isSuper || isSystemFlag != 'Y'">
              <el-button v-if="currentDataId && treeData.length == 0" @click="createNode(null)">添加选项
              </el-button>
              <span v-if="currentDataId" class="text-gray" style="font-size: 10px;">
                上下拖动选项可进行排序</span>
            </div>
            <div v-if="currentDataId" style="border: #f4f4f4 solid 1px; padding: 10px 0;">
              <el-tree :data="treeData" node-key="id" default-expand-all :expand-on-click-node="false"
                :draggable="isSuper || isSystemFlag !='Y'" :allow-drop="nodeIndexCheck" @node-drop="afterDrop">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <span>{{ node.label }} -- {{ data.value }} </span>
                  <span v-show="isSuper || isSystemFlag != 'Y'">
                    <a href="#" class="text-blue" v-permission="'adminDictionary.edit'"
                      @click.prevent="() => editNode(data)" title="编辑"><i class="fa fa-edit"></i></a>
                    <a href="#" class="text-green pl-5" v-permission="'adminDictionary.add'"
                      @click.prevent="createNode(data)" title="创建平级"><i class="fa fa-hand-o-right"></i></a>
                    <a href="#" class="text-yellow pl-5" v-permission="'adminDictionary.add'"
                      @click.prevent="createChildNode(data)" title="创建下级"><i class="fa fa-hand-o-down"></i></a>
                    <a href="#" class="text-red pl-5" v-permission="'adminDictionary.delete'"
                      @click.prevent="removeNode(data)" title="删除"><i class="fa fa-trash"></i></a>
                  </span>
                </span>
              </el-tree>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submit"
      :submitLoading="submitLoading" :visible.sync="editFormVisible"></z-form-dialog>
    <z-form-dialog name="选项" :data="nodeData" :formProps="formProps" :fields="nodeFields" @submit="submitNode"
      :submitLoading="submitLoading" :visible.sync="editNodeFormVisible"></z-form-dialog>
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
import { generateTree, expendsTree } from '@/utils'

export default {
  mixins: [commonMixin],
  name: 'adminDictionary',
  components: {},
  data: function () {
    return {
      isSuper: false,
      isSystemFlag: false,
      api: this.$api.dictionary,
      name: '数据字典',
      columns: [
        { title: '字典类型', key: 'type', width: 140 },
        { title: '显示名称', key: 'label', width: 120 },
        { title: '详细描述', key: 'description' },
      ],
      fields: [
        { title: '字典类型', key: 'type', required: true },
        { title: '显示名称', key: 'label', required: true },
        {
          title: '是否系统管控',
          key: 'is_system',
          name: 'switch',
          props: { activeValue: 'Y', inactiveValue: 'N', disabled: false },
        },
        { title: '详细描述', key: 'description' },
        { title: '备注', key: 'remarks' },
      ],
      tableProps: {
        highlightCurrentRow: true,
        border: true,
      },
      currentDataId: 0,
      treeData: [],
      nodeData: {},
      nodeFields: [
        { title: '显示名称', key: 'label', required: true },
        { title: '数据值', key: 'value', required: true },
      ],
      editNodeFormVisible: false,
      indexChangeFlag: false,
      type: '',
    }
  },
  methods: {
    createItem() {
      this.data = _.cloneDeep(this.initData)
      let tmp = this.fields.find((x) => x.key == 'is_system')
      tmp.props.disabled = false
      this.editFormVisible = true
    },
    getChildrenTree: function (row) {
      this.currentDataId = row ? row.id : 0
      this.isSystemFlag = row?.is_system
      this.type = row ? row.type : ''
      this.indexChangeFlag = false
      this.refreshTree()
    },
    editNode: function (data) {
      this.nodeData = Object.assign({}, data)
      this.editNodeFormVisible = true
    },
    createNode: function (data) {
      if (data) {
        this.nodeData = { parent_id: data.parent_id }
      } else {
        this.nodeData = { parent_id: this.currentDataId }
      }
      this.editNodeFormVisible = true
    },
    createChildNode: function (data) {
      this.nodeData = { parent_id: data.id }
      this.editNodeFormVisible = true
    },
    formatAfterGet(data) {
      //依据实际需求处理
      let tmp = _.cloneDeep(data)
      let tmpField = this.fields.find((x) => x.key == 'is_system')
      tmpField.props.disabled = true
      return tmp
    },
    submitNode: function () {
      let url = this.api + 'add'
      let data = Object.assign({}, this.nodeData)
      data.type = this.type
      if (!data.value || !data.label) {
        this.$message({
          message: '显示名称和数据值不能为空',
          type: 'error',
        })
        return
      }
      delete data.children
      this.submitLoading = true
      this.$request(url, data, 'post')
        .then((r) => {
          this.submitLoading = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.editNodeFormVisible = false
          this.refreshTree()
        })
        .catch(() => {
          this.submitLoading = false
        })
    },
    removeNode: function (data) {
      this.$confirm('确定要删除这条记录？', '操作确认').then(() => {
        this.pageLoading = true
        this.$request(this.api + 'delete/' + data.id, {}, 'post')
          .then((r) => {
            this.pageLoading = false
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.refreshTree()
          })
          .catch(() => {
            this.pageLoading = false
          })
      })
    },
    saveIndex: function () {
      var tmp = expendsTree(this.treeData)
      var data = []
      for (let i in tmp) {
        data.push({
          id: tmp[i].id,
          sorting: i,
        })
      }
      this.pageLoading = true
      let url = this.api + 'sorting'
      this.$request(url, data, 'post')
        .then((r) => {
          this.pageLoading = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.indexChangeFlag = false
          this.refreshTree()
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    nodeIndexCheck: function (draggingNode, dropNode, type) {
      if (dropNode.data.parent_id == draggingNode.data.parent_id) {
        return type === 'prev' || type === 'next'
      }
    },
    afterDrop: function () {
      this.indexChangeFlag = true
    },
    refreshTree: function () {
      if (this.currentDataId) {
        this.pageLoading = true
        this.$request(this.api + 'getchildren', { parentId: this.currentDataId })
          .then((r) => {
            this.pageLoading = false
            this.treeData = generateTree(r, 'id', 'parent_id', this.currentDataId)
          })
          .catch(() => {
            this.pageLoading = false
          })
      } else {
        this.treeData = []
      }
    },
  },
  created: function () {
    this.getList()
    this.$request(this.$api.user + 'checksuperuser').then((r) => {
      console.log(r)
      this.isSuper = r
    })
  },
}
</script>


<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  padding-right: 8px;
}
</style>
